package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.util.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.dto.course.CourseDto;
import com.qk.entity.Course;
import com.qk.management.mapper.CourseMapper;
import com.qk.management.service.CourseService;
import com.qk.vo.CourseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseMapper courseMapper;

    @Override
    public PageResult<CourseVO> getCourseList(CourseDto courseDto) {
        PageHelper.startPage(courseDto.getPage(), courseDto.getPageSize());
        List<CourseVO> courseList = courseMapper.getCourseList(courseDto);
        Page<CourseVO> rs = (Page<CourseVO>) courseList;
        return PageResult.<CourseVO>builder()
                .total((int) rs.getTotal())
                .rows(courseList)
                .build();
    }

    @Override
    public void deleteById(Integer courseid) {
        courseMapper.deleteById(courseid);
    }

    @Override
    public void addCourse(Course course) {

        boolean b = BeanUtil.hasNullField(course, "id", "subject", "name", "price", "target", "createTime", "updateTime");
        if (b){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        course.setCreateTime(LocalDateTime.now());
        course.setUpdateTime(LocalDateTime.now());
        courseMapper.insert(course);
    }

    @Override
    public Course selectById(Integer courseid) {
        return courseMapper.selectById(courseid);
    }

    @Override
    public void updateCourse(Course course) {
        course.setUpdateTime(LocalDateTime.now());
        courseMapper.updateCourse(course);
    }

    @Override
    public List<Course> selectList() {
        List<Course> courseList = courseMapper.selectList();
        return courseList;
    }

    @Override
    public List<Course> selectBySubject(Integer  subject) {
        List<Course> courseList = courseMapper.selectBySubject(subject);
        return courseList;
    }
}
